import {reqGetVerificationCode, reqLogout, reqUserInfo, reqUserLogin} from "@/api";


const state = {
    verificationCode: '',
    token: localStorage.getItem('TOKEN') || '',
    userInfo: {}
}
const actions = {
    // 获取验证码
    async getVerificationCode({commit}, phoneNumber) {
        const result = await reqGetVerificationCode(phoneNumber);
        (result)
        if (result.code === 200) {
            commit('GETVERCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    },
    // 登陆
    async login({commit}, loginData) {
        const result = await reqUserLogin(loginData)
        if (result.code === 200) {
            commit('LOGIN', result.data.token)
            localStorage.setItem('TOKEN', result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    },
    // 获取用户信息
    async getUserInfo({commit}) {
        const result = await reqUserInfo();
        if (result.code === 200) {
            commit('GETUSERINFO', result.data)
        }
    },
    // 退出登陆
    async logout({commit}) {
        const result = await reqLogout();
        if (result.code === 200) {
            // 提交至mutations清空相应的数据
            (result)
            commit('CLEAR')
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    }
}
const mutations = {
    GETVERCODE(state, data) {
        state.verificationCode = data
    },
    LOGIN(state, data) {
        state.token = data
    },
    GETUSERINFO(state, data) {
        state.userInfo = data
    },
    CLEAR(state) {
        state.token = ''
        state.userInfo = {}
        localStorage.removeItem('TOKEN')
    }
}
const getters = {
    nickName(state) {
        return state.userInfo.nickName
    },
    phone(state) {
        return state.userInfo.phone
    },
    password(state) {
        return state.userInfo.password
    }
}
export default {
    state,
    actions,
    mutations,
    getters
}